<template>
  <div class="app-container">
    <h1>角色管理-图片上传</h1>

    <el-form ref="form" :model="form" label-width="100px">

      <el-form-item label="头像">

        <el-upload class="avatar-uploader" name="attach" action="http://localhost:8080/upload/image"
          :show-file-list="false"
          :headers="tokenHeader"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="form.avator" :src="form.avator" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>


        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form-item>

    </el-form>



  </div>
</template>

<script>
  import {getToken } from '@/utils/auth.js'
  export default {
    name: 'Role',
    data() {
      return {
        form: {
          avator: undefined
        },
        tokenHeader: {
          'X-Token': getToken()
        }
      }
    },
    methods: {
      onSubmit() {

      },
      // ajax提交成功了返回数据 res后台结果, file当前文件
      handleAvatarSuccess(res, file) {
        console.log(res)
        console.log(file)
        this.form.avator = res.url
      },
      // 调用ajax之前的验证，必须为true
      beforeAvatarUpload(attach) {

        const isAllowed =  this.allowImageExtend(attach.type);
        const isLt2M = attach.size / 1024 / 1024 < 2;

        if (!isAllowed) {
          this.$message.error('上传头像图片只能是 jpg,gif,png 格式!');
        }

        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isAllowed && isLt2M;
      },
      // 是否支持文件类型
      allowImageExtend(filetype){
         const allowList=['image/jpeg','image/png','image/jpg','image/gif']
         let resultList=allowList.filter(function(value, index, array){
           return  value=== filetype;
         })
         return resultList.length>0;
      }

    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }

  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
</style>
